package dbinit.csv;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.StringTokenizer;
import dbinit.InitCategory;
import dbinit.csv.csvreader.CsvReader;

public class ImportCategory {

	public static void doImport(String cateName,String path,String type)
	{
		if(InitCategory.getCategoryByNameAndPath(cateName, path) == null)
    	{
			StringTokenizer pathsep = new StringTokenizer(path , "/") ;
			String parent = new String("/") ;
			Long parentUuid = 0L ;
			Long uuid = null ;
			while(pathsep.hasMoreTokens())
			{
				String newCateName = pathsep.nextToken() ; 
				String newPath = path.substring(0, path.indexOf(newCateName)) + newCateName;
				int depth = 0 ;
				if(InitCategory.getCategoryByNameAndPath(newCateName, newPath) == null)
				{
					depth = (new StringTokenizer(newPath , "/")).countTokens();
					uuid = InitCategory.doinit(newCateName ,depth ,newPath, parentUuid, type) ;
				}
				else
				{
					uuid = InitCategory.getCategoryByNameAndPath(newCateName, newPath).getUuid();
				}
				parent =  newCateName ;
				parentUuid = uuid ;
			}
	    }
	}
	public static void doImport(String Filename)
	{
		String filepath="source/";

		try {
			CsvReader productdata = new CsvReader(filepath+Filename);
			productdata.readHeaders();
			int count = 0;
			while (productdata.readRecord())
			{
				count ++ ;
				String cateName=productdata.get("Category Name");
				String path=productdata.get("path");
				String type=productdata.get("type");
				doImport(cateName,path,type);
			}
		}
		catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{
		// TODO Auto-generated method stub
		doImport("D:/advspace/AdvProp/source/category.csv");
	}

}
